package com.example.classcommunity3.service;

import com.alibaba.fastjson.JSON;
import com.example.classcommunity3.dao.HomeworkDao;
import com.example.classcommunity3.model.Homework;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class HomeworkService {

    @Autowired
    HomeworkDao homeworkDao;

    @Autowired
    SubmitHomeworkService submitHomeworkService;

    public String findHomeworkBySubCode(String subCode) {
        /**
         @describe 找到一门课下的所有作业
         @param [subCode]
         @return java.lang.String
         @date 2018/6/7
         */
        List<Homework> list = homeworkDao.findByHSubCode(subCode);
        String json = JSON.toJSONString(list);

        return json;
    }

    public String findHomeworkTitleByHId(Long hId) {
        /**
         @describe 查找作业标题
         @param [hId]
         @return java.lang.String
         @date 2018/6/10
         */
        Homework homework = homeworkDao.findByHId(hId);
        String hTitle = homework.gethTitle();

        return hTitle;
    }

    public Long addHomeWork(String subCode, String title, String item, String deadLine) {
        /**
         @describe 发布作业
         @param [subCode, title, item, deadLine]
         @return java.lang.Long
         @date 2018/6/7
         */
        Homework homework = new Homework();

        homework.sethSubCode(subCode);
        homework.sethTitle(title);
        homework.sethTitle(title);
        homework.sethItem(item);
        homework.sethDeadLine(deadLine);
        homeworkDao.save(homework);

        Long homeworkId = homework.gethId();

        return homeworkId;
    }

    public boolean deleteHomeworkByHid(Long hId) {
        /**
         @describe 指定id，删除作业
         @param [hId]
         @return boolean
         @date 2018/6/6
         */
        boolean b = false;

        Homework homework = homeworkDao.findByHId(hId);
        if (homework != null) {
            //删除homeWork表中的数据
            try {
                homeworkDao.delete(homework);
                b = true;
                //判断是否有人提交作业
                if (submitHomeworkService.isSubmitEmpty(hId)) {
                    try {//删除submitHomework表中学生提交的作业数据
                        b = submitHomeworkService.deleteByHomeworkId(hId);
                    } catch (Exception e) {
                        b = false;
                    }
                }

            } catch (Exception e) {
                b = false;
            }
        } else {
            b = false;
        }
        return b;
    }

    public boolean deleteHomeworkBySubCode(String subCode) {
        /**
         @describe 删除一门科目下的所有作业
         @param [subCode]
         @return boolean
         @date 2018/6/11
         */
        try {
            homeworkDao.deleteByHSubCode(subCode);
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
